package com.example.exam.service.impl;

import com.example.exam.pojo.Exception.ServiceException;
import com.example.exam.mapper.TExamPaperMapper;
import com.example.exam.mapper.TTextContentMapper;
import com.example.exam.pojo.vo.ExamPaperVO.*;
import com.example.exam.pojo.vo.QuestionVO.QuestionStandardVO;
import com.example.exam.pojo.vo.TextContentVO.TextContentStandardVO;
import com.example.exam.service.IExamPaperService;
import com.example.exam.tools.JsonPage;
import com.example.exam.tools.JsonUtil;
import com.example.exam.tools.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Transactional
@Service
@Slf4j
public class ExamPaperServiceImpl implements IExamPaperService {

    @Autowired
    private TExamPaperMapper examPaperMapper;

    @Autowired
    private QuestionServiceImpl questionServiceImpl;

    @Autowired
    private TTextContentMapper textContentMapper;

    @Override
    public JsonPage<ExamPaperStandardVO> getAllExamPaperByPage(ExamPaperStandardVO examPaperStandardVO) {
        log.debug("开始处理【分页查询试卷列表】的业务");
        PageHelper.startPage(examPaperStandardVO.getPageIndex(), examPaperStandardVO.getPageSize());
        List<ExamPaperStandardVO> listByPage = examPaperMapper.findExamPaper(examPaperStandardVO);
        return JsonPage.restPage(new PageInfo<>(listByPage));
    }

    @Override
    public String edit(ExamPaperEditStandardVO examPaperEditStandardVO) {
        log.debug("开始处理【修改/添加试卷】的业务");
        final int[] count = {0};
        final int[] score = {0};

        //获取参数提交的试卷内容，里面包含大标题名称和题目列表
        List<FrameTextContentVO> frameTextContentVOList=examPaperEditStandardVO.getTitleItems().stream().map(t->{
            FrameTextContentVO frameTextContentVO=new FrameTextContentVO();
            //对于每个大标题t，把它的名称赋值给frameTextContentVO的name
            frameTextContentVO.setName(t.getName());
            count[0] +=t.getQuestionItems().size();
            //对于每个大标题t,把它的题目列表赋值给frameTextContentVO的questionItems
            List<FrameContentVO> f=t.getQuestionItems().stream().map(i->{
                //对于每个题目i，把它的ID和序列号itemOrder赋值给frameContentVO
                FrameContentVO frameContentVO=new FrameContentVO();
                frameContentVO.setId(i.getId());
                frameContentVO.setItemOrder(i.getItemOrder());
                score[0]+=i.getScore();
                return frameContentVO;
            }).collect(Collectors.toList());
            frameTextContentVO.setQuestionItems(f);
            return frameTextContentVO;
        }).collect(Collectors.toList());

        //设置题目数量、试卷总分
        examPaperEditStandardVO.setQuestionCount(count[0]);
        examPaperEditStandardVO.setScore(score[0]);
        //把修改的试卷对象转成字符串，存到content中
        String content = JsonUtil.toJsonStr(frameTextContentVOList);
        //如果是时段试卷，设置起始、结束时间
        if(examPaperEditStandardVO.getPaperType()==4){
            examPaperEditStandardVO.setLimitStartTime(examPaperEditStandardVO.getLimitDateTime().get(0));
            examPaperEditStandardVO.setLimitEndTime(examPaperEditStandardVO.getLimitDateTime().get(1));
        }

        int row1=0;
        int row2=0;
        String response;

        if(examPaperEditStandardVO.getId()==null){
            if(textContentMapper.countByContent(content)==0){
                //向t_text_content表中插入数据
                log.debug("即将向数据库中插入数据：{}", content);
                row1=textContentMapper.insert(content);
            }
            int id = textContentMapper.getIdByContent(content);
            examPaperEditStandardVO.setFrameTextContentId(id);
            row1=1;

            log.debug("即将向数据库中插入数据");
            examPaperEditStandardVO.setDeleted(false);
            examPaperEditStandardVO.setCreateUser(2);
            row2= examPaperMapper.insert(examPaperEditStandardVO);
            response="添加试卷成功";
            if (row1 != 1) {
                String message = "添加试卷失败！服务器忙，请稍后再尝试！错误代码【2023.3.13】";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_INSERT, message);
            }
        }
        else {
            if(textContentMapper.countByContent(content)==0){
                //向t_text_content表中更新数据
                log.debug("即将向数据库中更新数据：{}", content);
                TextContentStandardVO textContentStandardVO=new TextContentStandardVO();
                textContentStandardVO.setId(examPaperEditStandardVO.getFrameTextContentId());
                textContentStandardVO.setContent(content);
                row1=textContentMapper.update(textContentStandardVO);
            }
            else{
                int id=textContentMapper.getIdByContent(content);
                examPaperEditStandardVO.setFrameTextContentId(id);
                row1=1;
            }
            log.debug("即将向数据库中更新数据");
            row2 = examPaperMapper.update(examPaperEditStandardVO);
            response="修改试卷成功";
        }

        if (row2 != 1) {
            String message = "修改试卷失败！服务器忙，请稍后再尝试！错误代码【2023.3.13】";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        return response;
    }

    /**
     * 根据试卷ID查询试卷所有内容，回显至修改页面
     * @param id
     * @return
     */
    @Override
    public ExamPaperEditStandardVO getEditStandardById(Integer id){
        log.debug("开始处理【根据id查询试卷，进入编辑界面】的业务");
        ExamPaperEditStandardVO editStandardById = examPaperMapper.getEditStandardById(id);
        //如果是时段试卷，可修改它的起始和结束时间
        if(editStandardById.getPaperType()==4) {
            List<String> limitDateTime = Arrays.asList(editStandardById.getLimitStartTime(),editStandardById.getLimitEndTime());
            editStandardById.setLimitDateTime(limitDateTime);
        }
        List<ExamPaperTitleItemVO> examPaperTitleItemVOS1 = null;
        //把试卷的内容转成对象
        List<ExamPaperTitleItemVO> examPaperTitleItemVOS = JsonUtil.toJsonListObject(editStandardById.getContent(), ExamPaperTitleItemVO.class);
        log.debug("根据id查询试卷,examPaperTitleItemVOS={}",examPaperTitleItemVOS);
        //获取试卷的大标题列表
        examPaperTitleItemVOS1= examPaperTitleItemVOS.stream().map(t -> {
            //获取试卷每个大标题对应的题目列表
            List<QuestionStandardVO> questionItemsVO = t.getQuestionItems().stream().map(i -> {
                QuestionStandardVO standardById = questionServiceImpl.getStandardById(i.getId());
                standardById.setItemOrder(i.getItemOrder());
                return standardById;
            }).collect(Collectors.toList());
            log.debug("根据id查询试卷,questionItemsVO={}",questionItemsVO);
            t.setQuestionItems(questionItemsVO);
            return t;
        }).collect(Collectors.toList());
        editStandardById.setTitleItems(examPaperTitleItemVOS1);
        log.debug("根据id查询试卷,editStandardById={}",editStandardById);
        //返回试卷的所有内容
        return editStandardById;
    }


    //删除
    @Override
    public void delete(Integer id) {
        log.debug("开始处理【删除试卷】的业务");
        int row = examPaperMapper.deleteId(id);
        if (row <= 0) {
            String message = "删除题目失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

}
